package com.lagou.edu.utils;

import java.io.File;
import java.io.FileFilter;
import java.io.UnsupportedEncodingException;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;

public class ComponentScanUtil {
    private ComponentScanUtil() {

    }

    private static ComponentScanUtil componentScanUtil = new ComponentScanUtil();

    List<String> beanList = new ArrayList<String>();

    public static ComponentScanUtil getInstance() {
        return componentScanUtil;
    }

    public List<String> getSacnBean(String pkg) {
        String pkgDir = pkg.replaceAll("\\.", "/");
        URL url = getClass().getClassLoader().getResource(pkgDir);
        //处理中文路径问题
        String path = null;
        try {
            path = java.net.URLDecoder.decode(url.getPath(), "utf-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        File file = new File(path);
        File fs[] = file.listFiles(new FileFilter() {

            @Override
            public boolean accept(File file) {
                String fName = file.getName();
                if (file.isDirectory()) {
                    try {
                        getSacnBean(pkg + "." + fName);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                } else {
                    //判断文件后缀是否为.
                    if (fName.endsWith(".class")) {
                        return true;
                    }
                }
                return false;
            }
        });
        for (File f : fs) {
            String fName = f.getName();
            if (fName.contains("$")) {
                continue;
            }
            fName = fName.substring(0, fName.lastIndexOf("."));

            beanList.add(pkg+"."+fName);
        }
        return beanList;
    }
}

